﻿using UnityEngine;
using ZFramework.Runtime;

namespace ZGame
{
    public class FGuiUIFormHelper : MonoBehaviour, IUIFormHelper
    {
        public Object InstantiateUIForm(Object uiFormAsset)
        {
            return Instantiate(uiFormAsset);
        }
        
        public IUIForm CreateUIForm(Object uiFormInstance, IUIGroup uiGroup, object userData)
        {
            GameObject go = uiFormInstance as GameObject;
            if (go == null)
            {
                Log.Error("UI form instance is invalid.");
                return null;
            }

            Transform transform = go.transform;
            transform.SetParent(((MonoBehaviour)uiGroup.Helper).transform);

            FGuiUIFormLogicBase fairyGuiFormLogic = go.GetComponent<FGuiUIFormLogicBase>();
            fairyGuiFormLogic.InitUIPanel(uiGroup, userData);
            
            return go.GetOrAddComponent<UIForm>();
        }
        
        public void ReleaseUIForm(string assetPath, Object uiFormInstance)
        {
            if (uiFormInstance != null)
            {
                FGuiUIFormLogicBase fairyGuiFormLogic = ((GameObject) uiFormInstance).GetComponent<FGuiUIFormLogicBase>();
                fairyGuiFormLogic.DeInitUIPanel();
                Destroy(uiFormInstance);
            }

            GameEntry.resourceManager.UnloadAsset(assetPath);
        }
    }
}